# -*- coding: UTF-8 -*-
# Author:JackyMao
# Blog:https://blog.csdn.net/xiaokai1999
import os
import win32clipboard
import tkinter
from tkinter import messagebox
from tkinter import filedialog
from PlayListParse import PlayListParse
from MusicDownload import MusicDownLoad
import time

def clipboard_get():
    """
    返回剪贴板数据
    :return:
    """
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()
    out_txt.insert('end',data)
    out_txt.see('end')
    return data

def click_file_button():
    """
    当打开filedialog按钮被点击时执行该函数
    :return:
    """
    save_path = filedialog.askdirectory(title="选择一个文件夹")
    file_path.set(save_path+"/")

def click_start_button():
    """
    当下载按钮被点击时执行该函数
    :return:
    """
    select = music_lbx.curselection()
    if len(select) == 0:
        messagebox.showerror(title="错误",message="没有选择音乐平台!")
    else:
        platform_name = music_lbx.get(select) 
        save_path = file_path.get()
        if len(save_path) == 0:
            messagebox.showerror(title="错误",message="没有填写保存地址!")
        elif not os.path.isdir(save_path):
            messagebox.showerror(title="错误",message="文件夹不存在") 
        else:
            failed_num = 0
            success_num = 0
            plp = PlayListParse()
            ids = plp.Parse(platform_name)
            md = MusicDownLoad()
            md.SetDownLoadPath(save_path)
            out_txt.insert('end',"---------------------一共"+(str(len(ids)))+"个----------------------\n")
            out_txt.see('end')
            for i in range(len(ids)):
                out_txt.insert('end',"---------------------第"+str(i+1)+"个开始---------------------\n")
                out_txt.see('end')
                md.SetMusicUrl(platform_name,ids[i])
                if(md.RequestMusicParse(out_txt)):
                    if md.DownLoadMusic(out_txt) == 0:
                        md.DownLoadLrc(out_txt)
                        success_num+=1
                    else:
                        failed_num+=1
                    out_txt.insert('end',"---------------------第"+str(i+1)+"个结束---------------------\n")
                    out_txt.insert('end',"---------------------还剩"+(str(len(ids)-i-1))+"个----------------------\n")
                    out_txt.see('end')
                    window.update()
                    time.sleep(3)
            out_txt.insert('end',"---------------------成功"+str(success_num)+"个---------------------\n")
            out_txt.insert('end',"---------------------失败"+str(failed_num)+"个---------------------\n")
            out_txt.see('end')
            messagebox.showinfo(title="提示",message="所有音乐下载完成")

def click_edit_button():
    """
    当按钮被点击时执行该函数
    :return:
    """
    pl = PlayListParse()
    pl.GetPath()
    parse_txt_path = pl.path + "parse.txt"
    if os.path.isfile(parse_txt_path):
        f = os.open(parse_txt_path,os.O_RDWR|os.O_TRUNC)  # 以清零读写写文件
        os.write(f,clipboard_get().encode())
        os.close(f)
    else:
        f = os.open(parse_txt_path,os.O_CREAT)
        os.close(f)
if __name__ == "__main__":
    window = tkinter.Tk()
    music_platforms = tkinter.StringVar()
    file_path = tkinter.StringVar()
    music_platforms.set(("网易云音乐","QQ音乐"))
    window.geometry("415x200")                              # 设置窗口400像素宽，200像素高
    window.title("MusicDownloadTool    by:JackyMao")        # 软件名称
    music_lbl = tkinter.Label(window,text="音乐平台:")
    music_lbl.place(x=5,y=5)
    music_lbx = tkinter.Listbox(window,listvariable=music_platforms,width=10,height=1)
    music_lbx.place(x=60,y=5)
    parse_edit = tkinter.Button(window,text="Edit_parse_txt",command=click_edit_button)
    parse_edit.place(x=300,y=2)
    file_lbl = tkinter.Label(window,text="文件保存:")
    file_lbl.place(x=5,y=30)
    file_txt = tkinter.Entry(window,textvariable=file_path)
    file_txt['state'] = 'disabled'
    file_txt.place(x=60,y=30)
    open_btn = tkinter.Button(window,text="打开",command=click_file_button)
    open_btn.place(x=205,y=25)
    start_btn = tkinter.Button(window,text="下载",command=click_start_button)
    start_btn.place(x=245,y=25)
    scrollbar = tkinter.Scrollbar(window) # 开启滚动条
    scrollbar.pack(side="right", fill="y")
    out_txt = tkinter.Text(window,width=55,height=10,yscrollcommand=scrollbar.set)
    scrollbar.config(command=out_txt.yview)
    out_txt.place(x=5,y=60)
    window.mainloop()
    